import React, { useState, useMemo, useEffect } from 'react';
import classNames from 'classnames';
import { connect } from 'dva';
import { StateWithHistory } from 'redux-undo';
import { Input, Tabs, Radio, Modal, Select } from 'antd';
import {
  Category,
  ComptTplType,
  ResourceItem,
  PointDataItem,
} from '@/ui-components/common';
import uiCompt from '@/ui-components/index';
import ResourceItemRender from '@/renderer/ResourceItemRender';
import CollapsedHandler from '@/components/CollapsedHandler';
import DragTarget from './DragTarget';
import req from '@/utils/req';
import { uuid, firstLetterToLowerCase } from '@/utils/tool';
import styles from './index.less';

const resourceTypes = [
  { id: 'courseware', name: '课件' },
  { id: 'video', name: '视频' },
  { id: 'audio', name: '音频' },
  { id: 'richText', name: '富文本' },
  { id: 'animation', name: '动画' },
  { id: 'question', name: '试题' },
  { id: 'paper', name: '试卷' },
];
const ResourceLibrary = (props: {
  name: string;
  components: ComptTplType[];
  pstate: {
    pageData: {
      width: number;
      height: number;
      widthScale: number;
      heightScale: number;
    };
    pointData: PointDataItem[];
    curPoint: any;
  };
  canvasId: string;
  allType: string[];
  dispatch: Dispatch;
}) => {
  const { schemaH5 } = uiCompt;
  const { components, canvasId, dispatch, pstate } = props;
  const [{ id: defaultResourceType }] = resourceTypes;
  const [resourceType, setResourceType] = useState(defaultResourceType);
  const [{ component: defaultComponent }] = components;
  const [component, setComponent] = useState(defaultComponent);
  const componentChange = (e) => {
    setComponent(e.target.value);
  };

  const [activeItem] = components.filter(
    (item) => item.component === component,
  );

  let pointData = pstate ? pstate.pointData : [];

  const [leftColla, setLeftColla] = useState(false); // 物料面板折叠
  const changeLeftColla = useMemo(() => {
    return (c: boolean) => {
      setLeftColla(c);
    };
  }, []);

  const [dataList, setDataList] = useState([]);
  useEffect(() => {
    req.get(`/api/${firstLetterToLowerCase(resourceType)}/list`).then((res) => {
      res && setDataList(res.data);
    });
  }, [resourceType]);

  const [modalConfig, setModalConfig] = useState({});
  const [modalContent, setModalContent] = useState({ name: '', path: '' });
  const modalContentRender = useMemo(() => {
    if (modalContent) {
      const { name, path } = modalContent;
      return (
        <div>
          <div>名称：{name}</div>
          <div>路径：{path}</div>
        </div>
      );
    }
  }, [modalContent]);

  const onView = (data: ResourceItem) => {
    const { config } = data;
    const { name, path } = config;
    setModalConfig((v) => ({ ...v, visible: true, title: name, footer: null }));
    setModalContent({
      name,
      path,
    });
  };

  const onAdd = (data: ResourceItem) => {
    let id = uuid(6, 10);
    dispatch({
      type: 'editorModel/addPointData',
      payload: {
        id,
        item: data,
        point: {
          i: id,
          x: 0,
          y: 0,
          w: data.config.fontSize,
          h: data.config.fontSize,
        },
      },
    });
  };

  return (
    <>
      <div
        className="flex bg-panel h100p"
        style={{
          transition: 'all ease-in-out 0.5s',
          transform: `translateX(${leftColla ? '-300px' : '0px'})`,
        }}
      >
        <div className="flex flex-col w300 h100p">
          <div className="pl16 lh44 fsz14 bdb1">{props.name}</div>
          <div className="pt16 px16">
            <div className="relative">
              <Input
                placeholder="输入名称或ID搜索"
                style={{ paddingRight: 32, height: 28 }}
              />
              <span
                className="absolute fsz24 iconfont icon-sousuo1"
                style={{ right: 8, top: '50%', marginTop: '-18px' }}
              ></span>
            </div>
          </div>
          <div className="pt16 px16">
            <div className="flex items-center justify-between px8 lh28 bg-nav bdrs4">
              <span>章节</span>
              <span className="iconfont icon-tingshuojinglian-xiayiye"></span>
            </div>
          </div>
          <div className="pt16 px16">
            <div className="flex items-center justify-between px8 lh28 bg-nav bdrs4">
              <span>知识点</span>
              <span className="iconfont icon-tingshuojinglian-xiayiye"></span>
            </div>
          </div>
          <div className="pt16 px16">
            <Select
              className="w100p bg-nav bdrs4"
              placeholder="用途"
              allowClear={true}
            >
              <Select.Option value="1">备课包</Select.Option>
              <Select.Option value="2">精品授课包</Select.Option>
              <Select.Option value="3">知识点包</Select.Option>
              <Select.Option value="4">微课包</Select.Option>
              <Select.Option value="5">课程介绍</Select.Option>
              <Select.Option value="6">学习目标</Select.Option>
            </Select>
          </div>
          <div className="flex items-center pt16 px16 lh20">
            <span className="pr12">呈现方式：</span>
            <Radio.Group value={component} onChange={componentChange}>
              {components.map((value: ComptTplType) => (
                <Radio key={value.component} value={value.component}>
                  {value.conponentName}
                </Radio>
              ))}
            </Radio.Group>
          </div>
          <div className="pt16">
            <Tabs
              activeKey={resourceType}
              className="defaultTabs"
              onTabClick={setResourceType}
            >
              {resourceTypes.map((item: { id: string; name: string }) => (
                <Tabs.TabPane tab={item.name} key={item.id}></Tabs.TabPane>
              ))}
            </Tabs>
          </div>
          <div className="flex1 overflow-x-hidden pt8 pb8 w100p pl10 overflow-y-auto">
            {dataList?.map(
              (value: { name: string; thumb: string }, i: React.Key) => {
                const config = {
                  resourceType, // 资源类型
                  ...(schemaH5 as any)[component].config, // 默认参数值
                  ...value, // 具体参数值
                };
                const item = {
                  ...activeItem,
                  config,
                  editableData: (schemaH5 as any)[component].editableData,
                };
                return (
                  <div className="fl pt8 pb8 px6" key={i}>
                    <DragTarget item={item} canvasId={canvasId}>
                      <React.Suspense fallback="loading">
                        <ResourceItemRender
                          item={item}
                          onView={onView}
                          onAdd={onAdd}
                        />
                      </React.Suspense>
                    </DragTarget>
                  </div>
                );
              },
            )}
          </div>
        </div>
        <CollapsedHandler
          align="vertical"
          direction="left"
          isCollapsed={leftColla}
          onToggle={() => changeLeftColla(!leftColla)}
        />
      </div>
      <Modal
        {...modalConfig}
        centered={true}
        onCancel={() => setModalConfig({ visible: false })}
      >
        {modalContentRender}
      </Modal>
    </>
  );
};

export default connect((state: StateWithHistory<any>) => {
  return {
    pstate: state.present.editorModel,
  };
})(ResourceLibrary);
